package com.xatu.yl.storeshopping.activity.Fragment;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.namespace.R;
import com.xatu.yl.storeshopping.activity.ShoppingInfoActivity;
import com.xatu.yl.storeshopping.vo.ShopInfo;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class UserHomeFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private View root;
    private EditText search;
    private ProgressBar refresh;

    private ListView pro_list;
    private TextView hint;
    private List<ShopInfo> shopInfoList = new ArrayList<>();
    //定义一个用来存放CommitData类型的集合
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //如果不存在，则创建
        if(root==null){
            root=inflater.inflate(R.layout.user_fragment_home, container, false);
        }


        //上导航栏，点击切换首页的展示内容
        search=root.findViewById(R.id.search);
        search.setOnClickListener(this);
        //搜索框的提示文字
        hint = root.findViewById(R.id.hint);
        //设置初始为未选中状态
        search.setFocusable(false);
        search.setFocusableInTouchMode(false);
        refresh=root.findViewById(R.id.refresh);
        pro_list=root.findViewById(R.id.pro_list);

        //设置事件监听
        search.setOnClickListener(this);
        refresh.setOnClickListener(this);

        //设置数据
        for(int i=0;i<10;i++){
            shopInfoList.add(new ShopInfo("","多赞","123","2￥/个","大家案发地撒欧弟的风"));
        }
        //绑定适配器,设置适配器

        pro_list.setAdapter(new ShopListAdapter());
        pro_list.setOnItemClickListener(this);
        return root;
    }

    //上册导航栏
    //为点击设计事件监听
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.search){
            //不管之前是否为选中状态
            //这里都设置选中
            search.setFocusable(true);
            search.setFocusableInTouchMode(true);
            //同时点击搜索框的时候，将文字取消
            hint.setText("");
        }
    }

    //点击列表项
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //跳转到商品界面
        startActivity(new Intent(getActivity(), ShoppingInfoActivity.class));
    }

    //适配器，加载整个pro_list中的内容
    public class ShopListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return shopInfoList.size();
        }

        @Override
        public Object getItem(int i) {
            return shopInfoList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View item = View.inflate(getActivity().getApplicationContext(), R.layout.shopper_pro_list_items, null);
            /**
             * shop_icon：商品图标
             * shop_name：商品名称
             * shop_sale_month：商品月销量
             * shop_price：商品价格
             * shop_description：商品描述
             */
            ImageView shop_icon = item.findViewById(R.id.shop_icon);
            TextView shop_name = item.findViewById(R.id.shop_name);
            TextView shop_sale_month = item.findViewById(R.id.shop_sale_month);
            TextView shop_price = item.findViewById(R.id.shop_price);
            TextView shop_description = item.findViewById(R.id.shop_description);


            //从集合中获取数据
            ShopInfo shopInfo = shopInfoList.get(i);

            // 图片
            if(shopInfo.getShop_icon().equals("")){
                shop_icon.setImageResource(R.drawable.error_photo);
            }else{
                new LoadImageTask(shop_icon).execute(shopInfo.getShop_icon());
            }

            shop_name.setText(shopInfo.getShop_name());
            shop_sale_month.setText(shopInfo.getShop_sale_month());
            shop_price.setText(shopInfo.getShop_price());
            shop_description.setText(shopInfo.getShop_description());

            return item;
        }
    }


    /**
     * 1.网络请求和图片加载：
     * 在 AsyncTask 的 doInBackground 方法中，我们执行网络请求，获取指定URL的图片数据流，并通过 BitmapFactory.decodeStream 方法将其解码为 Bitmap 对象。
     * 2.异步加载：
     * 使用 AsyncTask 来异步执行图片加载操作，确保在主线程之外进行网络请求，以避免阻塞主线程，从而保持应用的响应性。
     * 3.显示图片：
     * 在 onPostExecute 方法中，我们检查解码后的 Bitmap 是否为空，如果不为空，则将其设置到预先定义的 ImageView 中显示出来。
     * 4.为了避免 NetworkOnMainThreadException 异常，不能在主线程中执行网络请求。因此，使用 AsyncTask 或者其他异步加载方式是推荐的做法。
     */

    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView imageView;
        public LoadImageTask(ImageView imageView){
            this.imageView = imageView;
        }
        @Override
        protected Bitmap doInBackground(String... strings) {
            String imageUrl = strings[0];
            Bitmap bitmap = null;
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}


